<script setup lang="ts">
    import { ref, onMounted } from 'vue'
    import { useRouter } from 'vue-router'
    import { addressListAPIRes, addressDeleteAPIRes } from '@/api'
    import { useAddress } from '@/store/address.ts'

    const router = useRouter()
    const userAddress = useAddress()
    const listData = ref<any>([])

    const onAdd = () => {
        router.push({
            path: '/address/edit'
        })
    }
    const onEdit = (id: number) => {
        router.push({
            path: '/address/edit',
            query: { id }
        })
    }
    const onDelete = async(id: number) => {
        await addressDeleteAPIRes(id)
        getList()
    }
    const onItem = (item: any) => {
        if (router.options.history.state.back != '/my') {
            let opt = JSON.parse(JSON.stringify(item))
            opt.address = opt.province + opt.address
            userAddress.setAddress(opt)
        }
        router.back()
    }
    const getList = async() => {
        const { data } = await addressListAPIRes()
        listData.value = data
    }

    onMounted(() => {
        getList()
    })
</script>

<template>
    <van-nav-bar left-arrow fixed placeholder safe-area-inset-top :border="false" @click-left="router.back()" />
    <van-cell-group inset v-for="item in listData" :key="item.id" class="mt-2.5">
        <van-cell value-class="flex-none" @click="onItem(item)">
            <van-tag v-if="item.defaultAddress" round size="medium" color="#7C6186">默认</van-tag>
            <template #title>
                <div class="flex items-center text-base text-[#333]">
                    <span class="mr-4 text-lg font-bold">{{ item.name }}</span>
                    <span>{{ item.phone }}</span>
                </div>
            </template>
            <template #label>
                <div class="flex items-center">
                    <van-icon name="location-o" color="#333" :size="18" />
                    <span class="ml-1 text-base text-[#666]">{{ item.province + item.address }}</span>
                </div>
            </template>
        </van-cell>
        <div class="py-2.5 px-4 text-right">
            <van-button round icon="edit" size="small" color="#7C6186" @click="onEdit(item.id)" />
            <van-button round icon="delete-o" size="small" color="#7C6186" class="ml-3" @click="onDelete(item.id)" />
        </div>
    </van-cell-group>
    <van-empty v-if="listData.length == 0" image-size="100" description="暂无地址" />
    <div class="h-14 pt-2.5 van-safe-area-bottom box-content">
        <div class="mb-2.5 h-full"></div>
    </div>
    <div class="fixed bottom-0 left-0 right-0 pt-2.5 px-8 van-safe-area-bottom border-t bg-white">
        <van-button block color="#7C6186" class="mb-2.5" @click="onAdd">新增地址</van-button>
    </div>
</template>